package com.yan.yanbi.mq;

import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
import com.rabbitmq.client.DeliverCallback;

/**
 * fanout消费者代码
 *
 * @author yhn
 * @version 1.0
 * @description
 * @date 2024/3/2 13:59
 */
public class FanoutConsumer {
    //声明交换机
    private static final String FANOUT_EXCHANGE_NAME = "fanout-exchange";

    public static void main(String[] args) throws Exception {
        //创建连接工厂
        ConnectionFactory factory = new ConnectionFactory();
        factory.setHost("47.109.81.239");
        factory.setUsername("yhnyhn123");
        factory.setPassword("1658450511");

        Connection connection = factory.newConnection();
        //创建两个通道
        Channel channel1 = connection.createChannel();
        Channel channel2 = connection.createChannel();
        //声明交换机
        channel1.exchangeDeclare(FANOUT_EXCHANGE_NAME, "fanout");

        // 创建队列1员工小红,并绑定队列与交换机
        String queueName1 = "xiaohong_queue";
        channel1.queueDeclare(queueName1, true, false, false, null);
        channel1.queueBind(queueName1, FANOUT_EXCHANGE_NAME, "");
        // 员工小蓝
        String queueName2 = "xiaolan_queue";
        channel2.queueDeclare(queueName2, true, false, false, null);
        channel2.queueBind(queueName2, FANOUT_EXCHANGE_NAME, "");

        System.out.println(" [*] =========================================");

        //创建交付回调函数1
        DeliverCallback deliverCallback1 = (consumerTag, delivery) -> {
            //将消息转化为字符串
            String message = new String(delivery.getBody(), "UTF-8");
            System.out.println(" [x] Received '" + message + "'");
        };

        DeliverCallback deliverCallback2 = (consumerTag, delivery) -> {
            String message = new String(delivery.getBody(), "UTF-8");
            System.out.println(" [x] Received '" + message + "'");
        };

        // 监听消息
        channel1.basicConsume(queueName1, true, deliverCallback1, consumerTag -> {
        });
        channel2.basicConsume(queueName2, true, deliverCallback2, consumerTag -> {
        });
    }
}
